//
//  KSDateUtil.m
//  test
//
//  Created by Mac on 2018/12/27.
//

#import "KSDateUtil.h"

NSString* ks_strFromDate(NSDate* date,KSDateFormat dateFormat,NSTimeZone* timeZone){
    NSDateFormatter* formatter = ks_dateFormatter();
    formatter.dateFormat = dateFormat;
    [formatter setTimeZone:timeZone];
    
    return [formatter stringFromDate:date];
}

NSDate* ks_dateFromStr(NSString* str,KSDateFormat dateFormat,NSTimeZone* timeZone){
    NSDateFormatter* formatter = ks_dateFormatter();
    formatter.dateFormat = dateFormat;
    [formatter setTimeZone:timeZone];
    return [formatter dateFromString:str];
}


NSTimeInterval ks_secondFromNow(void){
    return ks_secondFromDate([NSDate date]);
}

NSTimeInterval ks_secondFromDate(NSDate* date){
    return [date timeIntervalSince1970];
}

NSDate* ks_dateFromSecond(NSTimeInterval second){
    return [NSDate dateWithTimeIntervalSince1970:second];
}


NSTimeInterval ks_msecFromNow(void){
    return ks_msecFromDate([NSDate date]);
}

NSTimeInterval ks_msecFromDate(NSDate* date){
    return ks_secondFromDate(date) * 1000;
}

NSDate* ks_dateFromMsec(NSTimeInterval msec){
    return ks_dateFromSecond(msec * 0.001);
}


NSTimeInterval ks_secondFromStr(NSString* str,KSDateFormat dateFormat,NSTimeZone* timeZone){
    NSDate* date = ks_dateFromStr(str, dateFormat,timeZone);
    return ks_secondFromDate(date);
}

NSString* ks_strFromSecond(NSTimeInterval second,KSDateFormat dateFormat,NSTimeZone* timeZone){
    NSDate* date = ks_dateFromSecond(second);
    return ks_strFromDate(date, dateFormat,timeZone);
}

NSTimeInterval ks_msecFromStr(NSString* str,KSDateFormat dateFormat,NSTimeZone* timeZone){
    NSDate* date = ks_dateFromStr(str, dateFormat,timeZone);
    return ks_msecFromDate(date);
}

NSString* ks_strFromMsec(NSTimeInterval msec,KSDateFormat dateFormat,NSTimeZone* timeZone){
    return ks_strFromSecond(msec / 1000, dateFormat,timeZone);
}


static NSDateFormatter* _formatter = nil;
NSDateFormatter* ks_dateFormatter(void){
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    });
    return _formatter;
}
